<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Tgtui extends Base
{
    /**
     * 已支付订单取消后的数据，需要审核
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'sale_status' => ['>',1]
            ];

            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school|orderno|name|idcard|backno'] = ['like', '%' . $params['school'] . '%'];
            }
            // 状态
            if(isset($params['o_status']) && $params['o_status'] != ''){
                $where['type'] = $params['o_status'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['fromtype'] = $params['type'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_tgorder')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_tgorder')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('sale_status asc,sale_time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }

    /**
     * 同意
     */
    public function orderYesSend(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $tui = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->field('user_id,sale_status')
            ->find();
        if($tui['sale_status'] != 2){
            return json(['code'=>100,'msg'=>'只有待审核的才可以同意']);
        }
        $param  = [
            'sale_status'=>3,
            'update_time'=>$today,
        ];
        $res = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->update($param);
        if($res){
//            $title = '取消订单成功通知';
//            $content = '由客服检验取消订单没有问题，款项将在7个工作日内原路退回您的付款账户。';
//            allInNotice($title,$content,4,$tui['user_id'],$order_id,2);
//            try{
//                $this->Jpush(1, $tui['user_id'], '取消订单成功通知', ['n_id' => $order_id,'type' => 2,'n_type' => 4]);
//            }catch(\Exception $e){
//
//            }
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'失败']);
        }
    }
    /**
     * 拒绝
     */
    public function orderNo(){
        extract(input());
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $tui = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->field('user_id,sale_status')
            ->find();
        if($tui['sale_status'] != 2){
            return json(['code'=>100,'msg'=>'只有待审核的才可以拒绝']);
        }
        $param  = [
            'sale_status'=>4,
            'update_time'=>$today,
        ];
        $res = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->update($param);
        if($res){
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'失败']);
        }
    }


    /**
     * 退款申请
     * @return \think\response\Json
     */
    public function orderTuiMoneyBefore(){
        extract(input());
        if(Request::instance()->isPost()){
            $order_id = input('tui_id');
            $today = date('Y-m-d H:i:s');
            $order = Db::table('up_offline_tgorder')
                ->where('id',$order_id)
                ->field('user_id,sale_status,sale_master_status,money')
                ->find();
            if($order['sale_status'] != 3){
                return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
            }
            if($order['sale_master_status'] != 1 && $order['sale_master_status'] != 3){
                return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
            }
            $refund_price = round($refund_price,2);
            if($refund_price <= 0 || $refund_price > $order['money']){
                return json(['code'=>100,'msg'=>'退款金额不能低于0且不能大于订单金额！']);
            }
            $param  = [
                'sale_master_status' => 2,
                'sale_money'=>$refund_price,
                'update_time' => $today,
            ];
            $last = Db::table('up_offline_tgorder')
                ->where('id',$order_id)
                ->update($param);
            if($last){
                return json(['code'=>200,'msg'=>'成功']);
            }else{
                return json(['code'=>100,'msg'=>'订单状态修改失败，新刷新重试！']);
            }
        }
        $tui = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->field('user_id,sale_status,sale_master_status')
            ->find();
        if($tui['sale_status'] != 3){
            return '只有同意且未退过款的才可以退款！';
            exit();
        }
		if($tui['sale_master_status'] != 1 && $tui['sale_master_status'] != 3){
            return '只有同意且未退过款的才可以退款！';
            exit();
        }
        return $this->fetch('tgtui/ordertuimoney',['tui_id'=>$order_id]);
    }
    /**
     * 已支付订单取消后的数据，需要审核
     */
    public function master(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'sale_status' => ['>',1],
                'sale_master_status' => 2
            ];

            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school|orderno|name|idcard|backno'] = ['like', '%' . $params['school'] . '%'];
            }
            // 状态
            if(isset($params['o_status']) && $params['o_status'] != ''){
                $where['type'] = $params['o_status'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['fromtype'] = $params['type'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_tgorder')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_tgorder')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('update_time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch('tgtui/master');
    }
    /**
     * 退款
     * @return \think\response\Json
     */
    public function orderTuiMoney(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $order = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->field('user_id,sale_status,sale_master_status,sale_money,money,orderno,tui_no,backno,type')
            ->find();
        if($order['sale_status'] != 3 || $order['sale_master_status'] != 2){
            return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
        }
        $refund_price = $order['sale_money'];
        if($refund_price <= 0 || $refund_price > $order['money']){
            return json(['code'=>100,'msg'=>'退款金额不能低于0且不能大于订单金额！']);
        }
        $param  = [
            'sale_master_status'=>4,
            'update_time' => $today,
        ];
        $payInfo = [
            'total_price' => $order['money'],
            'money' => $refund_price,
            'number' => $order['orderno']
        ];
        $refundNo = $order['tui_no'];
        if($order['type'] == 1){ //微信
            $tuiwx = new \app\admin\controller\Tuiwx();
            $res = $tuiwx->refundWx($payInfo,$refundNo);
        }elseif ($order['type'] == 2){ //支付宝
            $tuiali = new \app\admin\controller\Tuiali();
            $res = $tuiali->refund($payInfo,$refundNo);
        }else{
            $tuiali = new \app\admin\controller\Tuiupacp();
            $res = $tuiali->UpacpTuiKuan($refundNo,$refund_price,$order['backno']);
        }
        if($res['status'] == 200){
            $last = Db::table('up_offline_tgorder')
                ->where('id',$order_id)
                ->update($param);
            if($last){
                //平台退款
                allInRevenue(2,$refund_price,$order['user_id'],3,$order_id,session('username'),$order_id);
                return json(['code'=>200,'msg'=>'成功']);
            }else{
                return json(['code'=>100,'msg'=>'订单状态修改失败，请联系管理员将订单id为 '.$order_id.' 的订单改为已退款！']);
            }
        }else{
            return json(['code'=>100,'msg'=>$res['msg']]);
        }
    }
    /**
     * 退款拒绝
     * @return \think\response\Json
     */
    public function orderTuiMoneyNo(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $order = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->field('user_id,sale_status,sale_master_status,sale_money,money,orderno,tui_no,backno')
            ->find();
        if($order['sale_status'] != 3 || $order['sale_master_status'] != 2){
            return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以拒绝']);
        }
        $param  = [
            'sale_master_status'=>3,
            'update_time' => $today,
        ];
        $last = Db::table('up_offline_tgorder')
            ->where('id',$order_id)
            ->update($param);
        if($last){
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'订单状态修改失败，新刷新重试']);
        }
    }





    /**
     * 导出汇总
     * @return \think\response\Json
     */
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = 2;
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile|express_no'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            $map['order_push_erp'] = $type;
        }
        if(isset($cancelstatus) && $cancelstatus){
            $map['order_cancel_status'] = $cancelstatus;
        }else{
            $map['order_cancel_status'] = ['>=',2];
        }
        if(isset($paystatus) && $paystatus){
            $map['order_cancel_pay'] = $paystatus;
        }
        $field = [
            'order_no','order_back_order_id','total_price','express_original_price','all_goods_price',
            'all_good_nums', 'name','mobile','pay_type','pay_time',
            'school_name', 'is_send', 'order_cancel_status','order_cancel_pay','order_cancel_money',
            'new_old'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u', 'o.user_id=u.user_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($map)
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '订单号', '支付流水号', '总价（含邮费）', '运费', '衣服总价',
                '衣服总数量', '收件人', '收件电话', '支付平台', '支付时间',
                '学校名字', '是否发货', '订单是否取消', '是否已退款（取消了订单的才有）', '退款金额（取消了订单的才有）',
                '新老订单'
            ];
            $status = ['pay_type','is_send','order_cancel_status','order_cancel_pay','new_old'];
            $values = [
                'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'order_cancel_status' => [1 => '未取消',2 => '取消被拒',3 => '已同意取消',4 => '待审核']
                ,'order_cancel_pay' => [1 => '正常',2 => '未打款',3 => '已打款']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
            ];
            $res = exportExcel('orderCancel',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }

    /**
     * 导出明细
     * @return \think\response\Json
     */
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = 2;
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile|express_no'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            $map['order_push_erp'] = $type;
        }
        if(isset($cancelstatus) && $cancelstatus){
            $map['order_cancel_status'] = $cancelstatus;
        }else{
            $map['order_cancel_status'] = ['>=',2];
        }
        if(isset($paystatus) && $paystatus){
            $map['order_cancel_pay'] = $paystatus;
        }
        $field = [
            'o.order_no','unit_price','num','attr_id','goods_info',
            'goods_coding_unique','name','mobile', 'pay_type','pay_time',
            'school_name', 'is_send', 'o.new_old'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od','o.order_id=od.order_id','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            ->field($field)
            ->select();

        if($data){
            $cellname = [
                '订单号', '单价', '数量', '尺码', '产品信息',
                '唯一条码', '收件人', '收件电话', '支付平台', '支付时间',
                '学校名字', '是否发货', '新老订单'
            ];
            $status = ['pay_type','is_send','new_old'];
            $values = [
                'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
            ];
            $res = exportExcel('orderCancelInfo',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }

}